package com.rchat.pocmini.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.forgetpwd.ForgetPwdMvpActivity;
import com.rchat.pocmini.activity.main.MainActivity;
import com.rchat.pocmini.activity.register.RegisterMvpActivity;
import com.rchat.pocmini.bean.LoginBean;
import com.rchat.pocmini.bean2eventbus.EventBusLoginBean;
import com.rchat.pocmini.global.BundleKeyGlobal;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by ljd on 2017/7/26.
 */

public class LoginPresenterImpl extends LoginContract.Presenter {

    /**
     * 第三方启动登入页面
     */
    private final String START4ACTION = "com.rchat.pocmini.intent.action.third.START";
    /**
     * 是否来自插件的启动
     */
    private boolean isStartFromThird = false;

    private boolean isLogin = false;

    @Override
    public void onPStart() {
        EventBus.getDefault().register(this);
        String intentAction = mActivity.getIntent().getAction();
        ALog.dTag("StartApp", "action === %s", intentAction);

        setAutoLoginBackgroundImage();
        setRememberPwdBackgroundImage();
        if (START4ACTION.equals(intentAction)) {
            isStartFromThird = true;
            login(getAccount(mActivity), getPwd(mActivity));
        } else {
            isStartFromThird = false;
            autoLoginIfUserCheck(mActivity);
        }
        String account = (String) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_USERNAME, "");
        String pwd = (String) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_PWD, "");
        mView.setAccountEditText(account);
        if ((boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, false)) {
            mView.setPwdEditText(pwd);
        }

    }

    @Override
    public void onPDestroy() {
        EventBus.getDefault().unregister(this);
        super.onPDestroy();
    }

    @Override
    void login(String userName, final String pwd) {
//        startPocService(null,"");
        if (isLogin) {
            return;
        }
        if (TextUtils.isEmpty(userName)) {
            mView.showShortToast(mActivity.getString(R.string.tip_account_empty));
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            mView.showShortToast(mActivity.getString(R.string.tip_pwd_empty));
            return;
        }
        mModel.saveAccount(mActivity, SPUtil.SPKeyGlobal.KEY_USERNAME, userName);
        mModel.saveAccount(mActivity, SPUtil.SPKeyGlobal.KEY_PWD, pwd);
        isLogin = true;
        mModel.login(userName, pwd, new HttpCallbackImpl<LoginBean>() {
            boolean keepDialog = false;
            @Override
            public void onStart() {
                mView.showLoading();
            }

            @Override
            public void onSuccess(LoginBean bean) {
                keepDialog = true;
                if (mView == null) {
                    return;
                }
                ALog.d("desc = %s", bean.getDesc());
                LoginBean.DataBean dataBean = bean.getData();
                if (null == dataBean) {
                    mView.showShortToast(mActivity.getString(R.string.tip_network_error));
                    return;
                }
                /**
                 * 首次安装的时候，数据库取出的会员状态值是-1，所以需要初始化为普通会员的状态：0
                 */
                int status = (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, -1);
                if (status == -1) {
                    SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, dataBean.getStatus());
                    status = (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, 0);
                }
                if (status != dataBean.getStatus()) {
                    SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, dataBean.getStatus());
                }
                SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_IS_ENABLEPTT, bean.getData().getEnablePTT());

                startPocService(dataBean, pwd);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                keepDialog = false;
                if (mView == null) {
                    return;
                }
                ALog.d("code = %s,message = %s", bean.getCode(), bean.getDesc());
                isLogin = false;
                switch (bean.getCode()) {
                    case HttpCodeGlobal.RES_CODE_305 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_account_empty));
                        break;
                    case HttpCodeGlobal.RES_CODE_306 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_pwd_empty));
                        break;
                    case HttpCodeGlobal.RES_CODE_400 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_pwd_error));
                        break;
                    case HttpCodeGlobal.RES_CODE_401 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_account_out_validity));
                        break;
                    case HttpCodeGlobal.RES_CODE_303 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_check_error));
                        break;
                    case HttpCodeGlobal.RES_CODE_418 + "":
                        mView.showShortToast(mActivity.getString(R.string.tip_login_failure_account_unexist));
                        break;
                    default:
                        mView.showNetError(bean.getCode(), bean.getDesc());
                        break;
                }

            }

            @Override
            public void onFinish() {
                if (null == mView) {
                    return;
                }
                if (!keepDialog){
                    mView.dismissLoading();
                }
            }
        });
    }


    @Override
    void autoLoginIfUserCheck(Context context) {
        if (isAutoLogin(context, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false)) {
            login(getAccount(context), getPwd(context));
        }
    }

    @Override
    void gotoRegisterActivity() {
        Intent intentResetPasswordActivity = new Intent();
        intentResetPasswordActivity.setClass(mActivity, RegisterMvpActivity.class);
        mActivity.startActivity(intentResetPasswordActivity);
    }

    @Override
    void gotoForgetPwdActivity() {
        Intent intentRegisterActivity = new Intent();
        intentRegisterActivity.setClass(mActivity, ForgetPwdMvpActivity.class);
        mActivity.startActivityForResult(intentRegisterActivity, 1);
    }

    @Override
    void gotoRechargeActivity() {
//        Intent intentRechargeActivity = new Intent();
//        intentRechargeActivity.setClass(mActivity, RechargeActivity.class);
//        intentRechargeActivity.putExtra("from_login_activity", true);
//        mActivity.startActivity(intentRechargeActivity);
    }

    @Override
    void loginFromRegisterActivity(Intent data) {
        String account = data.getStringExtra(SPUtil.SPKeyGlobal.KEY_USERNAME);
        String pwd = data.getStringExtra(SPUtil.SPKeyGlobal.KEY_PWD);
        boolean login = data.getBooleanExtra("login", false);
        boolean back = data.getBooleanExtra("back", false);
        if (back || login) {
            if (!"".equals(account) && null != account) {
                mView.setAccountEditText(account);
            }
        }
        if (login) {
            if (!checkLogin(account, pwd)) {
                mView.setPwdEditText(pwd);
                login(account, pwd);
                mModel.saveAccount(mActivity, SPUtil.SPKeyGlobal.KEY_USERNAME, account);
                mModel.saveAccount(mActivity, SPUtil.SPKeyGlobal.KEY_PWD, pwd);
            }
        }
    }

    @Override
    void setAutoLoginBackgroundImage() {
        mView.setAutoLoginBackgroundImage((boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false));
    }

    @Override
    void setRememberPwdBackgroundImage() {
        mView.setRememberPwdBackgroundImage((boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, false));
    }

    @Override
    void setIvAutoLoginCheck() {
        if ((boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false)) {
            mView.setAutoLoginBackgroundImage(false);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false);
        } else {
            mView.setAutoLoginBackgroundImage(true);
            mView.setRememberPwdBackgroundImage(true);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, true);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, true);
        }
    }

    @Override
    void setIvRememberPwdCheck() {
        if ((boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, false)) {
            mView.setRememberPwdBackgroundImage(false);
            mView.setAutoLoginBackgroundImage(false);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_AUTOLOGIN, false);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, false);
        } else {
            mView.setRememberPwdBackgroundImage(true);
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_REMEMBER_PWD, true);
        }
    }


    private boolean isAutoLogin(Context context, String key, boolean defaultValue) {
        return (boolean) SPUtil.get(context, key, defaultValue);
    }


    private String getAccount(Context context) {
        return (String) SPUtil.get(context, SPUtil.SPKeyGlobal.KEY_USERNAME, "");

    }

    private String getPwd(Context context) {
        return (String) SPUtil.get(context, SPUtil.SPKeyGlobal.KEY_PWD, "");
    }

    /**
     * 校验账号密码
     *
     * @param account 账号
     * @param pwd     密码
     * @return 是否符合格式
     */
    private boolean checkLogin(String account, String pwd) {
        if (TextUtils.isEmpty(account)) {
            mView.showShortToast(mActivity.getString(R.string.tip_account_empty));
            return true;
        }
        if (TextUtils.isEmpty(pwd)) {
            mView.showShortToast(mActivity.getString(R.string.tip_pwd_empty));
            return true;
        }
        return false;
    }

    /**
     * 在PocService中执行SDK账号登录
     * 回调接口onLogin执行post消息发送
     *
     * @param bean sdk登录返回的结果
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusLoginSDK(EventBusLoginBean bean) {
        if (bean == null || !bean.isTarget(this.getClass())) {
            return;
        }
        isLogin = false;
        ALog.d("current = %s", bean.getCurrentEvent());
        mView.dismissLoading();
        isLogin = false;
        if (bean.getCurrentEvent() == PocService.ACCOUNT_RESULT_OK) {
            //进入主界面
            Intent intent = new Intent();
            intent.setClass(mActivity, MainActivity.class);
            intent.putExtra(BundleKeyGlobal.INTENT_START_APP_THIRD, isStartFromThird);
            mActivity.startActivity(intent);
            mActivity.finish();
        }
    }

    private void startPocService(LoginBean.DataBean dataBean, String pwd) {
        Intent pocServiceIntent = new Intent(mActivity, PocService.class);
        Bundle bundle = new Bundle();
        bundle.putString(PocService.SDK_LOGIN_IPOCID, dataBean.getIpocId());
        bundle.putString(PocService.SDK_LOGIN_PWD, pwd);
        bundle.putString(PocService.SDK_LOGIN_EXPIREDATE, dataBean.getExpireDate());
//        bundle.putString(PocService.SDK_LOGIN_IPOCID, "111110000088");
//        bundle.putString(PocService.SDK_LOGIN_PWD, "123456");
//        bundle.putString(PocService.SDK_LOGIN_EXPIREDATE, "2020-02-09 14:41:36");
        pocServiceIntent.putExtras(bundle);
        mActivity.startService(pocServiceIntent);
    }
}
